<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/qs/6.10.1/qs.min.js"></script>
  </head>
  <body>
    <button id="btn">超时重新请求接口</button>

    <script>
      const service = axios.create({
        timeout: 1000, //超时时间
        retry: 4, // 请求次数
        baseURL: 'http://localhost:8080',
        retryDelay: 1000,
      });

      service.interceptors.request.use(
        (config) => {
          return config;
        },
        (error) => {}
      );

      service.interceptors.response.use(
        (res) => {
          return res;
        },
        (error) => {
          let config = error.config;

          if (!config || !config.retry) return Promise.reject(error);
          config.__retryCount = config.__retryCount || 0;
          //超出设置的次数 全部失败
          if (config.__retryCount >= config.retry) {
            console.log(error, 'error');
            return Promise.reject(error);
          }
          //累计请求次数
          config.__retryCount += 1;

          let backoff = new Promise(function (resolve) {
            setTimeout(function () {
              resolve();
            }, config.retryDelay || 1);
          });

          return backoff.then(function () {
            return service(config);
          });
        }
      );
      btn.addEventListener(
        'click',
        function () {
          service({
            url: '/testRepetition',
            method: 'GET',
          });
        },
        false
      );
    </script>
  </body>
</html>
